package com.kai.service.util;

import com.alibaba.fastjson.JSON;
import com.kai.service.data.dto.wechat.receive.TextMessageReceiveDto;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

public class XmlUtil {

    /**
     * xml字符串转对象
     *
     * @param xmlStr
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T xmlStrToObject(String xmlStr, Class<T> clazz) {
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshal = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);

            return JSON.parseObject(JSON.toJSONString(unmarshal.unmarshal(sr)), clazz);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * xml字符串转element
     *
     * @param xmlStr
     * @return
     */
    public static Element xmlStrToElement(String xmlStr) {
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(new StringReader(xmlStr));
            return read.getRootElement();
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对象转xml字符串
     *
     * @param obj
     * @return
     * @param <T>
     */
    public static <T> String objectStrToXml(T obj) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

            StringWriter sw = new StringWriter();
            marshaller.marshal(obj, sw);

            return sw.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String a = "<xml><ToUserName><![CDATA[gh_a1b480047ba2]]></ToUserName><FromUserName><![CDATA[oVZxV6r6SrsMA_qtr20ThZ8DkVwI]]></FromUserName><CreateTime>1681229149</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你好]]></Content><MsgId>24069416013887605</MsgId></xml>";
        TextMessageReceiveDto textMessageReceiveDto = xmlStrToObject(a, TextMessageReceiveDto.class);
        System.out.println(textMessageReceiveDto);

        System.out.println(objectStrToXml(textMessageReceiveDto));
    }
}
